# -*- coding: utf-8 -*-

from django import forms

from usuarios.models import Usuario

class LoginForm(forms.Form):
    usuario = forms.CharField()
    senha = forms.CharField(max_length=50, widget=forms.PasswordInput)

    def __init__(self, *args, **kwargs):
        super(LoginForm, self).__init__(*args, **kwargs)
        self.user_cache = None

    def clean(self):
        usuario = self.cleaned_data.get('usuario')
        senha = self.cleaned_data.get('senha')
        if usuario and senha:
            try:
                user = Usuario.objects.get(usuario__exact=usuario)
                if user.senha.lower() == senha.lower():
                    self.user_cache = user
            except Usuario.DoesNotExist, e:
                pass
            if self.user_cache is None:
                raise forms.ValidationError(u'Usuário e senha não conferem.')
        return self.cleaned_data

    def get_user(self):
        return self.user_cache

